package threadLearn.producerconsumer.v2;

import java.util.Random;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 生产者消费者 基于wait notify的实现
 * @author 12609
 *
 */
public class Producer implements Runnable{
	
	private Vector<String> queue;
	private int size;
	private static AtomicInteger count = new AtomicInteger(0);
	Random r = new Random();
	public Producer(Vector<String> queue, int size) {
		this.queue = queue;
		this.size = size;
	}

	@Override
	public void run() {
		
		while(true) {
			//如果队列满了就停止生产
			while(queue.size() == size) {
				synchronized (queue) {
					try {
						queue.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("队列已满，生产者正在等待。。。");
				}
			}
			
			//生产面包,加入队列,并通知消费者消费
			synchronized (queue) {
				String bread = "面包"+count.incrementAndGet();
				System.out.println(Thread.currentThread().getId()+"生产了"+bread);
				queue.add(bread);
				queue.notifyAll();
			}
		}
	}
	
}
